const fs = require("fs");
const path = require("path");
const minimatch = require("minimatch");

const currentWorkDir = process.cwd();
const configFile = path.resolve(currentWorkDir, "app-builder.json");
if (!fs.existsSync(configFile)) {
  return console.log(`配置文件不存在 ${configFile}`);
}

const config = require(configFile);
const configPath = config["app-builder"];

for (const config of configPath) {
  const fromPath = formalPath(config.from);
  const destPath = formalPath(config.to);
  fs.rmSync(destPath, {recursive: true, force: true});
  copyPath(fromPath, destPath, config.filter, config.exclude);
}

function copyPath(from, to, filter, exclude) {
  fs.mkdirSync(to, {recursive: true});

  const files = fs.readdirSync(from, {withFileTypes: true});
  for (const it of files) {
    const fromPath = path.join(from, it.name);
    const destPath = path.join(to, it.name);

    if (it.isFile()) {
      if (isMatch(fromPath, filter)) {
        if (exclude != null && exclude.length > 0 && isMatch(fromPath, exclude)) {
          continue;
        }

        try {
          fs.copyFileSync(fromPath, destPath);
          console.log(`✔ ${fromPath} => ${destPath}`);
        } catch (e) {
          console.log(`😒 ${fromPath} => ${destPath}`);
          console.error(e && e.message || e);
        }
      }
    } else if (it.isDirectory()) {
      copyPath(fromPath, destPath, filter, exclude);
    }
  }
}

function isMatch(file, filter) {
  if (!filter || filter.length === 0) {
    return true;
  }
  return filter.some(it => minimatch(file, it, {matchBase: true}));
}

function formalPath(p) {
  return path.isAbsolute(p) ? p : path.resolve(currentWorkDir, p);
}
